package sawyer;
/** FileIO.java
 * @author shadowimmage@gmail.com - Chase Sawyer
 * @date-original November 2012
 * University of Washington INFO 341 AU 2012
 * 
 * Generic property file load/save class.
 * @update May 2013:
 * - Appropriated fileIO class for use as general logging and program output.
 */

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.Date;

public class FileIO {
	private Path filepath;
	private BufferedReader reader;

	/** Creates a new object with the given filename. Will either read or write depending on the 
	 * actions called on it. Filename will be prepended with the date in the format of:
	 * MM-DD-YYYY-HH-MM-SS-
	 * @param filename - File name to be used in this instance.
	 */
	public FileIO(String filename) {
		Date t = new Date();
		String dateTime = String.format("%tm-%<td-%<tY-%<tH-%<tM-%<tS-", t);
		filename = dateTime + filename;
		filepath = Paths.get(filename);
		if (this.exists()) {
			try {
				reader = Files.newBufferedReader(filepath, Charset.defaultCharset());
			} catch (IOException e) {
				System.err.format("IOException: %s%n", e);
			}
		}
	}
	
	/** Checks for a file's existence against the filesystem.
	 * @return true if the file exists in the filesystem.
	 */
	public boolean exists() {
		if (Files.exists(filepath)) {
			return true;
		} else if (Files.notExists(filepath)) {
			return false;
		} else {
			return false;
		}
	}
	
	/** Checks if this file/path has read permissions for this program.
	 * @return true if the file is readable, false otherwise.
	 */
	public boolean isReadable() {
		if (this.exists() && Files.isReadable(filepath)) {
			return true;
		} else {
			return false;
		}
	}
	
	/** Checks if this file/path has write permission on the filesystem for this program.
	 * @return true if the file can be written to the filesystem.
	 */
	public boolean isWritable() {
		if (this.exists() && Files.isWritable(filepath)) {
			return true;
		} else {
			return false;
		}
	}
	
	public BufferedReader getFileReader() {
		return reader;
	}
	
	/** Writes a string of text to a plain text file on the filesystem with a path/filename 
	 * given by this instance (as passed to the constructor).
	 * @param text Plain text to be written to the filesystem.
	 */
	public void writeFile(String text) {
		if (this.isWritable()) {
			try {
				BufferedWriter writer = Files.newBufferedWriter(filepath, Charset.defaultCharset());
				writer.write(text, 0, text.length());
				writer.close();
			} catch (IOException e) {
				System.err.format("Could not access file for writing: %s%n", e);
			}
		} else {
			System.err.println("Could not open file for saving.");
		}
	}
}
